package com.lunasoft.client;

import com.lunasoft.protobuf.TESMsg;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @author Jierry
 * @version 2016/7/14.
 */
public class Client {
    public static final String HOST = "127.0.0.1";
    private static final int PORT = 9528;
    private static Logger logger = LoggerFactory.getLogger(Client.class);

    public static void main(String[] args) throws Exception {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        Client.connect(b, workerGroup);
    }

    static void connect(Bootstrap b, EventLoopGroup workerGroup) {
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                pipeline.addLast(new IdleStateHandler(20, 0, 0));
                pipeline.addLast(new ProtobufVarint32FrameDecoder());
                pipeline.addLast(new ProtobufDecoder(TESMsg.BasicMsg.getDefaultInstance()));
                pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
                pipeline.addLast(new ProtobufEncoder());
                pipeline.addLast(new ClientHandler());
            }
        });

        b.remoteAddress(HOST, PORT);
        b.connect().addListener((ChannelFuture channelFuture) -> {
            if (channelFuture.cause() != null) {
                logger.info("连接失败 Failed to connect: " + channelFuture.cause());
            }

            if (!channelFuture.isSuccess()) {
                logger.info("重连 listener:Reconnect");
                workerGroup.schedule(() -> connect(b, workerGroup), 10L, TimeUnit.SECONDS);
            }
        });
    }

}
